<?php
/**
 * Created by PhpStorm.
 * User: ytlmi
 * Date: 2018/2/2
 * Time: 18:58
 * 案件管理控制器，
 * 增删改查，分页输出
 */

namespace app\forensic\controller;

use app\common\controller\BaseController;
use app\forensic\model\Sample as SampleM;
use app\lab\controller\Frequency;
use app\lab\model\Person;
use app\lab\model\Kit;
use org\util\forensictool\ForensicCalculate;
use org\util\forensictool\WriteReport;
use think\Db;

class DNACase extends BaseController
{
    protected $model = 'app\forensic\model\DNACase';


    /**
     * @throws \Exception
     */
    public function getCaseList()
    {
        $inputData = input();
        $default = ['page' => 1, 'perPage' => 10];
        $query = array_merge($default, $inputData);
        $page = $query['page'];
        $perPage = $query['perPage'];
        $start = $perPage * ($page - 1);
        if (isset($query['options'])) {
            $options = $this->fixQueryWord($query['options']);
        }
        if (isset($options)) {
            $data = Db::table('forensic_case')->where($options)->limit($start, $perPage)->select();
        } else {
            $data = Db::table('forensic_case')->limit($start, $perPage)->select();
        }
        foreach ($data as $key => $item) {
            $data[$key]['request_date'] = date('Y-m-d', $item['request_date']);
            $data[$key]['create_time'] = date('Y-m-d', $item['create_time']);
        }

        return $data;
    }

    public function del(int $id)
    {
        $caseData=$this->M->where(['id'=>$id])->select();
        $a=new SampleM;
        if (isset($caseData[0])) {
            $samples=$caseData[0]->samples;
            if (is_array($samples)) {
                foreach ($samples as $role => $sample) {
                        $a->destroy(['sample_name'=>$sample['sample_name']]);
                }
            }
        }
        return parent::del($id);
    }

    /**
     * @param string $caseType 案件类型
     * @param string $sampleName0 父亲/已知样编号
     * @param string $sampleName1 孩子/未知样编号
     * @param string $frequencyName 基因频率库名称
     * @param string $sampleNameM 母亲编号
     * @return mixed
     * 根据样品名计算
     */
    public function calculate($caseType, $sampleName0, $sampleName1, $frequencyName, $sampleNameM = null)
    {
        try {
            $sampleModel = new SampleM();
            $freC = new Frequency();
            $genotypeM = [];
            $f = $sampleModel->where('sample_name', $sampleName0)->select();
            $c = $sampleModel->where('sample_name', $sampleName1)->select();
            $genotypeF = $f[0]['genotype'];
            $genotypeC = $c[0]['genotype'];
            if ($sampleNameM) {
                $m = $sampleModel->where('sample_name', $sampleNameM)->select();
                $genotypeM = $m[0]['genotype'];
            }

            $frequency = $freC->getFullFrequency($frequencyName);
            $mut = $freC->getAllMut($frequencyName);

            return ForensicCalculate::instance()
                ->setCaseType($caseType)
                ->setGenotypeF($genotypeF)
                ->setGenotypeM($genotypeM)
                ->setGenotypeC($genotypeC)
                ->setFrequency($frequency)
                ->setMutation($mut)
                ->calculate();
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param string $part 要生成的文档类型，如鉴定报告、交接单、检验记录
     * @param string $caseId 案件编号
     * @param string $frequencyName 使用的基因频率库名称
     * @return mixed
     * @throws \Exception
     *
     */
    public function makeDoc($part, $caseId, $frequencyName = null)
    {
            //验证$part
            $partMap = ['report'=>'', 'record'=>'-检验记录表', 'handover'=>'-交接单'];
            if (!isset($partMap[strtolower($part)])) return '错误的文档类型：' . $part;
            //案件数据
            $caseData = $this->M->get(['case_id' => $caseId])->toArray();
            //试剂盒信息
            $kitM = new Kit;
            $kit = $kitM->column('kit_name,kit_describe,kit_company,kit_lot', 'id');
            //配置信息
            $config = Config::instance()->getConfig();
            //基因频率库
            $freC = new Frequency();
            if (!$frequencyName) $frequencyName = $config['frequency'];
            $frequency = $freC->getFullFrequency($frequencyName);
            //突变率
            $mut = $freC->getAllMut($frequencyName);
            //鉴定人
            $appC = new Person();
            $app = $appC->where(['is_appraiser' => 1])->column('name,calling,number', 'id');
            //初始化、传递数据
            $action = WriteReport::instance()
                ->setCaseData($caseData)
                ->setKit($kit)
                ->setConfig($config)
                ->setFrequency($frequency)
                ->setMutation($mut)
                ->setAppraiser($app);
            //判断方法是否存在
            $method = 'make' . ucfirst(strtolower($part));
            if (is_callable(get_class($action), $method)) $action->$method();//生成
            $this->redirect('/report/forensic/' . $caseId . $partMap[$part] . '.docx');
            return true;
    }

    public function downloadDefaultDoc($type)
    {
        $typeMap = ['handover', 'record', 'report_qz', 'report_ty'];
        if (!in_array($type, $typeMap)) exit('错误的类型:' . $type);
        $this->redirect('/template/forensic/default/' . $type . '.docx');
    }

    public function uploadDoc()
    {
        $type = input()['type'];
        $typeMap = ['handover', 'record', 'report_qz', 'report_ty'];
        if (!in_array($type, $typeMap)) exit('错误的类型:' . $type);
        $file = request()->file('file');
        if ($file) {
            //保存文件
            $savePath = $_SERVER['DOCUMENT_ROOT'] . DS . 'template/forensic/';
            $file->move($savePath, $type . '.docx');
            return true;
        } else {
            return false;
        }
    }
    
    public function del(int $id)
    {
        $data=$this->M->where(['id'=>$id])->select();
        $caseData=$data[0]->toArray();
        $sampleM=new SampleM();
        foreach ($caseData['samples'] as $role=>$sample) {
            $sampleM->destroy(['sample_name'=>$sample['sample_name']]);
        }
        return parent::del($id);
    }


}